package nid.gallery.view 
{
	import flash.display.Sprite;
	import flash.events.AsyncErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.media.Video;
	import flash.net.NetConnection;
	import flash.net.NetStream;
	import flash.utils.Timer;
	import nid.gallery.IView;
	/**
	 * ...
	 * @author Nidin P Vinayakan
	 */
	public class VideoView extends Sprite implements IView
	{
		private var connection:NetConnection;
		private var buffer:Number=0;
		
		public var video:Video;
		public var stream:NetStream;
		public var uri:String;
		
		public function VideoView() 
		{
			video = new Video();
			addChild(video);
		}
		public function push(media:XML):void
		{
			clearVideo();
			align();
			uri = media.@src;
			newStream();
			trace('uri:' + uri );
		}
		protected function newStream():void
		{			
			if(stream != null)
			{
				stream.removeEventListener(AsyncErrorEvent.ASYNC_ERROR, forwardEvent);
				stream.removeEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
				stream.removeEventListener(IOErrorEvent.IO_ERROR, forwardEvent);
				stream.close();
				stream = null;
			}
		
			if(connection != null)
			{
				connection.removeEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
				connection.removeEventListener(IOErrorEvent.IO_ERROR, forwardEvent);
				connection.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, forwardEvent);
				connection.close();
				connection = null;
			}
			
			connection = new NetConnection();
			connection.connect(null);
			connection.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
			connection.addEventListener(IOErrorEvent.IO_ERROR, forwardEvent);
			connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, forwardEvent);
			
			stream = new NetStream(connection);
			stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, forwardEvent);
			stream.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
			stream.addEventListener(IOErrorEvent.IO_ERROR, forwardEvent);
			stream.client = this;
			
			video.attachNetStream(stream);
			
			stream.bufferTime = buffer;
			stream.receiveAudio(true);
			stream.receiveVideo(true);
			
			stream.play(uri);
		}
		
		private function onNetStatus(e:NetStatusEvent):void 
		{
			trace('code:'+ e.info.code);
		}
		public function onMetaData(infoObject:Object):void		
        {
			trace('duration:'+infoObject.duration);
		}
		private function clearVideo():void 
		{
			
		}
		public function clear():void
		{
			
		}
		public function align():void
		{
			
		}
		/**
		 *  Forward Events
		 */
		private function forwardEvent(e:Event):void 
		{
			dispatchEvent(e);
			trace('error:' + e.type);
		}
	}

}